﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Albon.Model;

namespace BLL
{
    public class OrderBLL
    {
        private readonly DAL.OrderDAL orderdal = new DAL.OrderDAL();
        private readonly OrderItemBLL orderitembll = new OrderItemBLL();
        /// <summary>
        /// 根据登录用户名获取表中未完成的订单
        /// </summary>
        public DataTable getNewOrder(string userName)
        {
            return orderdal.getOrder("userName='"+userName+"' and finished=0");
        }
        /// <summary>
        /// 获取未完成（进行中）订单的ID
        /// </summary>
        public string getNewOrderID(string userName)
        {
            DataTable dt = orderdal.getOrder("userName='" + userName + "' and finished=0");
            if (dt.Rows.Count > 0)
            {
                return dt.Rows[0]["ID"].ToString();
            }
            else return "";
        }
        /// <summary>
        /// 获取订单中订单项的名称和数量
        /// </summary>
        /// <returns></returns>
        public string getItemsDescribe(string orderid)
        {
            DataTable dtItem = orderitembll.getItemByOrderID(orderid);
            string list = "";
            foreach (DataRow dr in dtItem.Rows)
            {
                list +=dr["itemName"].ToString() + ":" + dr["quantity"].ToString()+"<br>";
            }
            return list;
        }

        /// <summary>
        /// 向orderItem中添加一个finished=0的临时订单
        /// </summary>
        public string addNewOrder(OrderInfo order)
        {
            return orderdal.addNewOrder(order);
        }

        /// <summary>
        /// 将临时订单中 finished=0改为finished=1,
        /// </summary>
        public bool finishOrder(OrderInfo order)
        {
            return orderdal.finishOrder(order);
        }

        /// <summary>
        /// 根据ID获取订单信息(包括已完成和未完成的订单)
        /// </summary>
        public DataTable getOrderByID(string id)
        {
            return orderdal.getOrder("ID="+id);
        }
        public string gerRefNoByID(string orderid)
        {
            DataTable dt=getOrderByID(orderid);
            if (dt.Rows.Count == 1)
            {
                return dt.Rows[0]["refNo"].ToString();
            }
            else
            {
                return "The Order is not exists!";
            }
        }
        /// <summary>
        /// 根据refNo获取订单信息
        /// </summary>
        public string checkRefNo(string refNo,string username)
        {
            DataTable dt=orderdal.getOrder("refNo='"+refNo+"' and userName ='"+username+"'");
            if (dt.Rows.Count > 0)
            {
                return "Exists";
            }
            else {
                return "OK";
            }
        }

        /// <summary>
        /// 立刻将订单投入生产，不必等待三天后
        /// </summary>
        public void pocessOrder(string orderid)
        {
            orderdal.processOrder(orderid);
        }

        /// <summary>
        /// 将订单放入回收站
        /// </summary>
        /// <returns></returns>
        public bool moveToRecycleBin(string orderid)
        {
            return orderdal.moveToRecycleBin(orderid);
        }
        /// <summary>
        /// 根据ID删除订单(同时删除所有订单项，及所有订单项的尺寸，样式，布料数据)
        /// </summary>
        public bool deleteOrder(string orderid)
        {
            return orderdal.deleteOrder(orderid);
        }

        /// <summary>
        /// 订单是否已经购买布料，全部购买返回true,只要有一块未买则返回fasle;
        /// </summary>
        public bool finishBuy(string orderid)
        {
            DataTable dtItem=orderitembll.getItemByOrderID(orderid);
            bool ret = true;
            foreach (DataRow drItem in dtItem.Rows)
            {
                ItemClothBLL itemclothbll=new ItemClothBLL();
                DataTable dtCloth=itemclothbll.getItemCloth(drItem["ID"].ToString());
                foreach (DataRow drCloth in dtCloth.Rows)
                {
                    if (drCloth["statusID"].ToString()=="1")
                    {
                        ret = false; break;
                    }
                }
            }
            return ret;
        }

        /// <summary>
        /// 判断订单是否已经提交 
        /// </summary>
        public bool isProcessed(string orderid)
        {
            DataTable dt = getOrderByID(orderid);
            bool ret = (Boolean.Parse(dt.Rows[0]["processed"].ToString()) || ((DateTime.Parse(dt.Rows[0]["createDate"].ToString()) < DateTime.Now.AddDays(-3))));
            return ret;
        }
        /// <summary>
        /// 返回订单的状态（unProcessed,BuyMe或者className）
        /// </summary>
        public string orderStatus(string orderid)
        {
            DataTable dt = orderdal .getOrder("finished=1 and ID="+orderid);
            if (!isProcessed(orderid))
            {
                return "unProcessed";
            }
            
            else if (!finishBuy(orderid) && dt.Rows[0]["classID"].ToString() != "2")
            {
                return "BuyMe";
            }
            else
            {
                return dt.Rows[0]["className"].ToString();
            }
        }

        /// <summary>
        /// 获取所有需要购买布料的订单，做为数据源绑定到repeater
        /// userName为空时显示所有BuyMe订单
        /// </summary>
        public DataTable getBuyMeOrder(string username)
        {
            DataTable dt = orderdal.getOrder("active=1 and finished=1 and userName like '%"+username+"%' order by createDate desc");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string orderid=dt.Rows[i]["ID"].ToString();
                if (orderStatus(orderid)!="BuyMe")
                {
                    dt.Rows[i].Delete();
                }
            }
            return dt;
        }

        /// <summary>
        /// 获取有新消息的订单
        /// </summary>
        /// <returns></returns>
        public DataTable getOrderWithNewMessage(string username, bool showall)
        {
            DataTable dt = new DataTable();
            if (showall)
            {
                dt = orderdal.getOrder("active=1 and finished=1 order by createDate Desc");
            }
            else
            {
                dt = orderdal.getOrder("active=1 and finished=1 and userName='"+username+"' order by createDate Desc");
            }
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string orderid = dt.Rows[i]["ID"].ToString();
                MessageBLL messagebll = new MessageBLL();
                if (!messagebll.hasNewMessage(orderid, username))
                {
                    dt.Rows[i].Delete();
                }
            }
            return dt;
        }
        /// <summary>
        /// 获取有未读消息的订单
        /// </summary>
        /// <returns></returns>
        public DataTable getOrderWithUnReadMessage(string username,bool showall)
        {
            DataTable dt = new DataTable();
            if (showall)
            {
                dt = orderdal.getOrder("active=1 and finished=1 order by createDate Desc");
            }
            else
            {
                dt = orderdal.getOrder("active=1 and finished=1 and userName='" + username + "' order by createDate Desc");
            }
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string orderid = dt.Rows[i]["ID"].ToString();
                MessageBLL messagebll = new MessageBLL();
                if (!messagebll.hasUnRead(orderid, username))
                {
                    dt.Rows[i].Delete();
                }
            }
            return dt;
        }

        /// <summary>
        /// 判断订单内是否有已完成的订单项
        /// </summary>
        public bool hasItems(string orderid)
        {
            DataTable dt=orderitembll.getItemByOrderID(orderid);
            return dt.Rows.Count>0;
        }
        /// <summary>
        /// 判断当前订单的发货是否已经延期（未在指定时间内发货）
        /// </summary>
        public bool isDelay(string orderid,DateTime shipdate)
        {
            if (!finishShip(orderid)&&(shipdate<DateTime.Now))
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 判断当前订单是否已经完成生产，等待发货
        /// </summary>
        public bool finishProduce(string orderid)
        {
            return finishBuy(orderid) && true;
        }
        /// <summary>
        /// 判断当前订单是否已经全部出货
        /// </summary>
        /// <returns></returns>
        public bool finishShip(string orderid)
        {
            bool ret = true;
            DataTable dt=orderitembll.getItemByOrderID(orderid);
            foreach (DataRow dr in dt.Rows)
            { 
                ShipBLL shipbll=new ShipBLL();
                if(!shipbll.finishShip(dr["ID"].ToString()))
                {
                    ret=false;
                    break;
                }
            }
            return ret;
        }
        /// <summary>
        /// 获取当前用户，同一客户的上一个订单
        /// </summary>
        public string getPreviousOrderRef(string orderid)
        {
            DataTable dt = orderdal.getPreviousOrder(orderid);
            if (dt.Rows.Count > 0)
            {
                return dt.Rows[0]["refNo"].ToString();
            }
            else {
                return "NULL";
            }
        }

        /// <summary>
        /// 获取当前订单所有者的国家信息
        /// </summary>
        public DataTable getCountry(string orderid)
        {
            return orderdal.getCountry(orderid);
        }


        //将orderonhoud中的订单移至orderinwork中
        public void putHoudOrderInWork(int invoiceNo)
        {
            DataTable dt=orderdal.getOrder("invoiceNo="+invoiceNo.ToString());
            if (dt.Rows.Count > 0)
            {
                if (decimal.Parse(dt.Rows[0]["classID"].ToString()) == 2)
                {
                    orderdal.moveOrderTo(int.Parse(dt.Rows[0]["ID"].ToString()), 1);
                }
            }
        }
        //修改订单类别
        public void MoveOrder(OrderInfo order)
        {
            orderdal.moveOrderTo(order.ID,order.classID );
        }
    }
}
